<?php
/**
 * Date: 2024-07-06
 */

namespace module\ai\model;

use think\model\Collection;
use think\model\relation\HasMany;

/**
 * AI通道
 * @property array $config
 * @property Collection $keys
 * @property Key $oneKey
 * @property array Config
 * @package module\ai\model
 */
class Channel extends \mof\Model
{
    protected $name = 'ai_channel';

    protected $type = [
        'config' => 'json',
    ];

    protected $scene = [
        'simple' => [
            'visible' => ['id', 'name']
        ]
    ];

    public function keys(): HasMany
    {
        return $this->hasMany(Key::class, 'flag', 'flag')
            ->where('status', 1);
    }

    public function oneKey(): ?Key
    {
        return $this->keys()->order('id', 'desc')->find();
    }

    public function getConfigAttr($value): array
    {
        $result = [];
        if ($value) {
            if ($config = json_decode($value, true)) {
                foreach ($config as $key => $val) {
                    if ($val === '') continue;
                    $result[$key] = is_numeric($val) ? floatval($val) : $val;
                }
            }
        }
        return $result;
    }

}